/*
 *    This file is part of ABAP To Phone, the application receives messages
 *    sent from an ABAP Server via C2DM  
 *    Copyright (C) 2011 J.Patterson
 *      
 *    This program is free software: you can redistribute it and/or modify
 *	  it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *   Adopted from the Apache License 2-licensed chrometophone project by Google Inc.
 *      
 */
package com.jasper.android.atp;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class RegistrationActivity extends Activity  {

	public static final String UPDATE_UI_ACTION = "com.jasper.atp.UPDATE_UI";
	public static final String REGISTER_ACTION = "com.google.android.c2dm.intent.REGISTER";
	public static final String UNREGISTER_ACITON = "com.google.android.c2dm.intent.UNREGISTER";
	public static final String nude = null;
	
	private TextView statusText;
	private TextView registerText;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//set custom title
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 
		setContentView(R.layout.registration);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
		setTitle(R.string.title_registration);
		
		statusText = (TextView) findViewById(R.id.status);
     	registerText = (TextView) findViewById(R.id.click_register);
		((Button) findViewById(R.id.register)).setOnClickListener(mRegisterButtonListener);
		
		Spinner accounts = (Spinner) findViewById(R.id.accounts);
		accounts.setAdapter(getGoogleAccounts(this));
		accounts.setPrompt(getString(R.string.accounts));
		
		registerReceiver(mUpdateReceiver, new IntentFilter(UPDATE_UI_ACTION));
		updateStatus();	
		
	}

	@Override
	public void setTitle(CharSequence title) {
		super.setTitle(title);
		((TextView) findViewById(android.R.id.title)).setText(title);
	}
	
	private boolean updateStatus() {
		SharedPreferences prefs = Prefs.get(this);
		Button registerButton = (Button) findViewById(R.id.register);
		
		String registrationID = prefs.getString(DeviceRegistrar.REGISTRATION_ID, null);
		if (registrationID == null) {
			statusText.setText(R.string.status_not_registered);
			registerButton.setText(R.string.register);
			registerText.setVisibility(TextView.VISIBLE);
			return false;
		} else {
			statusText.setText(R.string.status_registered);
			registerButton.setText(R.string.unregister);
            registerText.setVisibility(TextView.INVISIBLE);
			return true;
		}
	}
	
	private final OnClickListener mRegisterButtonListener = new OnClickListener() {
		public void onClick(View v) {
			
			SharedPreferences prefs = Prefs.get(getApplicationContext());
			String registrationID = prefs.getString(DeviceRegistrar.REGISTRATION_ID, null);
		
			if (registrationID == null) {  // register
				Spinner accounts = (Spinner) findViewById(R.id.accounts);
				SharedPreferences.Editor editor = prefs.edit();
				editor.putString(DeviceRegistrar.ACCOUNT_NAME, (String) accounts.getSelectedItem());
				editor.commit();

				// register
				Intent registrationIntent = new Intent(REGISTER_ACTION);
				registrationIntent.putExtra("app", PendingIntent.getBroadcast(
						RegistrationActivity.this, 0, new Intent(), 0));
				registrationIntent.putExtra("sender", Prefs.SENDER);
				startService(registrationIntent);
				statusText.setText(R.string.status_registering);
			} else {  // unregister
				Intent unRegisterIntent = new Intent(UNREGISTER_ACITON);
				unRegisterIntent.putExtra("app", PendingIntent.getBroadcast(
						RegistrationActivity.this, 0, new Intent(), 0));
				startService(unRegisterIntent);
				statusText.setText(R.string.status_unregistering);
			}
		}
	};	
	
	private ArrayAdapter<String> getGoogleAccounts(Context context) {
		//assumption maybe more than one account
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		Account[] accounts = AccountManager.get(context).getAccounts();
		for (Account account : accounts) {
			if (account.type.equals("com.google")) {
				adapter.add(account.name);
			}
		}
		return adapter;
	}
	
	private final BroadcastReceiver mUpdateReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			updateStatus();
			
			int status = intent.getIntExtra( DeviceRegistrar.STATUS_EXTRA, DeviceRegistrar.ERROR_STATUS);
            String msg = null;
            // determine status message
			switch (status) {
			case DeviceRegistrar.REGISTERED_STATUS:
				msg = context.getString(R.string.msg_registered);
				break;
			case DeviceRegistrar.BAD_REQUEST_STATUS:
				msg = context.getString(R.string.msg_badrequest);
				break;
			case DeviceRegistrar.ERROR_STATUS:	
				msg = context.getString(R.string.msg_error);
				break;
			case DeviceRegistrar.UNREGISTERED_STATUS:
				msg = context.getString(R.string.msg_unregistered);
				break;
			}
			 Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();    
		}
	};
}
